import React, { useEffect, useState } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import { useParams, history } from 'umi';
import {
    bindTradeUser,
    cancelTrade,
    checkoutPreview,
    getTradeDetail,
    modifyTrade,
    printCashierTicket,
    printOrderTicket,
    printTradeTicket,
} from '@/services/order';
import { getRestaurantTables } from '@/services/ant-design-pro/desk';
import { getUserByMobile, getUserDetail, getUserList } from '@/services/ant-design-pro/menber';
import { getProductList } from '@/services/ant-design-pro/product';
import { useDebounceFn } from '@ant-design/pro-components';
import {
    AutoComplete,
    Button,
    Card,
    Col,
    Divider,
    Empty,
    Form,
    InputNumber,
    message,
    Modal,
    Popconfirm,
    Row,
    Select,
    Spin,
    Switch,
    Table,
    Space,
    Typography,
    Tabs,
    Input,
} from 'antd';
import OrderStatusTag from '@/components/OrderStatus';
import AddOrderProductModal from '@/components/AddOrderProductModal';

const { Title, Text } = Typography;
const { Option } = Select;
const { TabPane } = Tabs;

// 定义类型
interface EditableCellProps extends React.HTMLAttributes<HTMLElement> {
    editing: boolean;
    dataIndex: string;
    title: any;
    inputType: 'number' | 'text';
    record: any;
    index: number;
    children: React.ReactNode;
}

interface OrderItem {
    id: number;
    no: string;
    status: number;
    item: {
        productId: number;
        productName: string;
        quantity: number;
        price: number;
        totalAmount: number;
        variantName?: string;
        variantId?: number;
    };
    payment: {
        originAmount: number;
        amount: number;
        adjust: number;
        discount: number;
    };
}

interface TradeDetail {
    id?: number;
    no?: string;
    status?: number;
    restaurantTable?: {
        id: number;
        name: string;
    };
    seat?: number;
    remark?: string;
    payment?: {
        originAmount: number;
        amount: number;
        adjust: number;
        discount: number;
    };
    orders?: OrderItem[];
    createdAt?: string;
    updatedAt?: string;
    user?: {
        id: number;
        username: string;
        mobile: string;
    } | null;
}

// 处理订单列表数据
const makeTradeOrderList = (orders?: OrderItem[]) => {
    if (!orders) return [];
    return orders.map((order) => {
        return {
            orderId: order?.id,
            productId: order?.item?.productId,
            variantId: order?.item?.variantId,
            quantity: order?.item?.quantity,
        };
    });
};

// 可编辑单元格组件
const EditableCell: React.FC<EditableCellProps> = ({
    editing,
    dataIndex,
    children,
    ...restProps
}) => {
    return (
        <td {...restProps}>
            {editing ? (
                <Form.Item
                    name={'quantity'}
                    style={{ margin: 0 }}
                    rules={[
                        {
                            required: true,
                            message: `请输入`,
                        },
                    ]}
                >
                    <InputNumber />
                </Form.Item>
            ) : (
                children
            )}
        </td>
    );
};

const OrderDetailPage: React.FC = () => {
    const params = useParams<{ id: string }>();
    const orderId = params?.id ? Number(params.id) : null;

    const [checkoutModalOpen, setCheckoutModalOpen] = useState(false);
    const [editOpen, setEditOpen] = useState(false);
    const [singleEditOpen, setSingleEditOpen] = useState(false);
    const [orderProductOpen, setOrderProductOpen] = useState(false);
    const [tradeDetail, setTradeDetail] = useState<TradeDetail>({});
    const [editParams, setEditParams] = useState<Record<string, any>>({});
    const [singEditParams, setSingleEditParams] = useState<Record<string, any>>({});
    const [productList, setProductList] = useState<any[]>([]);
    const [tableList, setTableList] = useState<any[]>([]);
    const [checkoutUser, setCheckoutUser] = useState<any>(null);
    const [menberInputVal, setMenberInputVal] = useState<string | null>(null);
    const [checkoutDetail, setCheckoutDetail] = useState<any>(null);
    const [checkoutBindedUser, setCheckoutbindedUser] = useState<any>(null);

    const [productListForm] = Form.useForm();
    const [editingKey, setEditingKey] = useState<string>('');
    const [editingOrderId, setEditingOrderId] = useState<number | null>(null);
    const [userOptions, setUserOptions] = useState<any[]>([]);
    const [loading, setLoading] = useState(false);

    const [editOrderForm] = Form.useForm();
    const [editSingleOrderForm] = Form.useForm();
    const [menberForm] = Form.useForm();

    // 获取订单详情
    const init = async ({ addOrderNum = null } = {}) => {
        if (!orderId) return;

        setLoading(true);
        const resp = await getTradeDetail(orderId);
        const { data } = resp;
        setTradeDetail(data);
        setLoading(false);

        if (data?.user?.id) {
            getMenber(data?.user?.id);
            setCheckoutbindedUser(true);
        }

        if (addOrderNum) {
            const orders = resp?.data?.orders;
            console.log('[orders]', orders);
            const addOrderList = orders?.slice(orders?.length - addOrderNum);
            console.log('[addOrderList]', addOrderList);
            const allPrint = addOrderList.map((item: any) => {
                return printOrderTicket(item.id);
            });

            await Promise.all(allPrint);
        }
    };

    // 编辑订单
    const handleEditOrder = async (
        tradeOrderList = makeTradeOrderList(tradeDetail?.orders),
        addOrderNum = null,
    ) => {
        if (!orderId) return;

        setLoading(true);
        console.log('[tradeDetail]', tradeDetail);

        const params = {
            id: orderId,
            tableId: tradeDetail?.restaurantTable?.id,
            tradeOrderList,
            ...editParams,
        };

        if (!tradeDetail?.restaurantTable?.id) {
            message.error('桌号有误，请刷新重试');
            setLoading(false);
            return;
        }

        console.log(tradeOrderList);
        const resp = await modifyTrade(params);

        if (resp.code === 0) {
            message.success('操作成功');
            setOrderProductOpen(false);
            init({ addOrderNum });
        }

        setLoading(false);
    };

    // 编辑商品
    const editOrderProductList = (record: any, id: number) => {
        const list = makeTradeOrderList(tradeDetail?.orders);
        const order = list.find((item) => item.orderId === id);
        productListForm.setFieldsValue(order);
        console.log('[order]', order);
        setEditingKey(record.id);
        setEditingOrderId(id);
    };

    // 保存编辑
    const saveOrderProductList = async (key: React.Key) => {
        try {
            const row = await productListForm.validateFields();
            const newData = makeTradeOrderList(tradeDetail?.orders);
            const index = newData.findIndex((item) => editingOrderId === item.orderId);

            if (index > -1) {
                const item = newData[index];
                newData.splice(index, 1, {
                    ...item,
                    ...row,
                });
                console.log('[newData]', newData);
                handleEditOrder(newData);
                setEditingKey('');
            } else {
                newData.push(row);
                setEditingKey('');
            }
        } catch (errInfo) {
            console.log('Validate Failed:', errInfo);
        }
    };

    // 获取商品列表
    const initProductList = async (params = {}) => {
        const resp = await getProductList({ ...params, status: 1 });
        const { list } = resp?.data;
        setProductList(list);
    };

    // 获取餐桌列表
    const initTable = async (areaId = undefined) => {
        const resp = await getRestaurantTables({ areaId });
        const { list } = resp?.data;
        setTableList(list);
    };

    useEffect(() => {
        if (orderId) {
            init();
            initProductList();
            initTable();
        }
    }, [orderId]);

    console.log('[editingKey]', editingKey);
    const isEditing = (record: any) => record.id === editingKey;

    // 商品表格列定义
    const ProductShowColumns = [
        {
            title: '产品名称',
            dataIndex: 'item',
            key: 'item',
            render: (_: any) => {
                return _.productName;
            },
        },
        {
            title: 'SKU',
            dataIndex: 'item',
            key: 'item',
            render: (_: any) => {
                return _.variantName || '无';
            },
        },
        {
            width: '135px',
            title: '价格',
            dataIndex: 'payment',
            key: 'payment',
            render: (_: any) => {
                return (
                    <>
                        <Row justify="space-between">
                            <Col>原价：</Col>
                            <Col>￥{_?.originAmount}</Col>
                        </Row>
                        <Row justify="space-between">
                            <Col>调整：</Col>
                            <Col>￥{_?.adjust}</Col>
                        </Row>
                        <Row justify="space-between">
                            <Col>折扣：</Col>
                            <Col>￥{_?.discount}</Col>
                        </Row>
                        <Row justify="space-between">
                            <Col>实际支付：</Col>
                            <Col>￥{_?.amount}</Col>
                        </Row>
                    </>
                );
            },
        },
        {
            title: '数量',
            dataIndex: 'quantity',
            key: 'quantity',
            editable: true,
            render: (_: any, record: any) => {
                return record?.item?.quantity;
            },
        },
        ...[
            tradeDetail?.status == 1
                ? {
                    title: '操作',
                    dataIndex: 'option',
                    valueType: 'option',
                    width: '200px',
                    render: (_: any, record: any) => {
                        const editable = isEditing(record);

                        return (
                            <Space wrap>
                                <Button
                                    size="small"
                                    onClick={() => {
                                        setSingleEditOpen(true);
                                        setSingleEditParams({
                                            orderId: record?.id,
                                            ...record?.item,
                                            price: record?.payment?.totalAmount,
                                        });
                                        editSingleOrderForm.setFieldsValue({
                                            totalAmount: record?.item?.totalAmount,
                                        });
                                    }}
                                    type="primary"
                                >
                                    折扣
                                </Button>

                                {editable ? (
                                    <>
                                        <Button
                                            type="primary"
                                            size="small"
                                            onClick={() => saveOrderProductList(record.key)}
                                        >
                                            保存
                                        </Button>
                                        <Popconfirm
                                            title="确认取消吗?"
                                            onConfirm={() => {
                                                setEditingKey('');
                                            }}
                                        >
                                            <Button danger type="primary" size="small">
                                                取消
                                            </Button>
                                        </Popconfirm>
                                    </>
                                ) : (
                                    <Button
                                        size="small"
                                        onClick={() => {
                                            editOrderProductList(record, record?.id);
                                        }}
                                        type="primary"
                                    >
                                        编辑
                                    </Button>
                                )}

                                <Popconfirm
                                    title="确认删除吗"
                                    key="delete"
                                    onConfirm={async () => {
                                        const tradeOrderList = makeTradeOrderList(tradeDetail?.orders).filter(
                                            (item) => item.orderId !== record.id,
                                        );
                                        handleEditOrder(tradeOrderList);
                                    }}
                                >
                                    <Button size="small" type="primary" danger>
                                        删除
                                    </Button>
                                </Popconfirm>
                            </Space>
                        );
                    },
                }
                : {},
        ],
    ];

    const mergedColumns = ProductShowColumns.map((col: any) => {
        if (!col.editable) {
            return col;
        }
        return {
            ...col,
            onCell: (record: any) => ({
                record,
                inputType: col.dataIndex === 'age' ? 'number' : 'text',
                dataIndex: col.dataIndex,
                title: col.title,
                editing: isEditing(record),
            }),
        };
    });

    // 结账预览
    const handlePreviewCheckout = async (_: any, vals: any) => {
        console.log('[vals]', vals);
        console.log('handlePreviewCheckout');
        const resp = await checkoutPreview(orderId!, {
            action: 'preview',
            ...vals,
            payMethod: 'cash',
        });
        console.log('[resp]', resp);
        setCheckoutDetail(resp?.data);
    };

    // 结账
    const handleCheckout = async () => {
        const resp = await checkoutPreview(orderId!, {
            action: 'pay',
            ...menberForm.getFieldsValue(),
            payMethod: 'cash',
        });

        if (resp.code === 0) {
            message.success('操作成功');

            init();
            setCheckoutModalOpen(false);

            if (localStorage.getItem('disableCheckoutPrint') !== 'true') {
                const resp = await printCashierTicket(orderId!);
                if (resp.code === 0) {
                    message.success('打印成功');
                }
            }
        }
    };

    // 根据手机号搜索会员
    const searchMenber = async (userMobile: string) => {
        const resp = await getUserByMobile({ mobile: userMobile });

        if (resp.code === 0) {
            setCheckoutUser(resp?.data);
        }
    };

    // 获取会员信息
    const getMenber = async (id: number) => {
        const resp = await getUserDetail(id);

        if (resp.code === 0) {
            setMenberInputVal(resp?.data?.username);
            setCheckoutUser(resp?.data);
        }
    };

    // 绑定会员
    const bindMenber = async () => {
        if (!checkoutUser?.id) return;

        const resp = await bindTradeUser(orderId!, { userId: checkoutUser.id });

        if (resp.code === 0) {
            message.success('绑定成功');
            setCheckoutbindedUser({
                status: 1,
            });
            init();
        }
    };

    // 搜索会员
    const { run: handleSearch } = useDebounceFn(async (val: string) => {
        const resp = await getUserList({
            keyword: val,
        });

        const options = resp?.data?.list?.map((item: any) => {
            return {
                label: item.username,
                value: item.id,
            };
        });

        setUserOptions(options);
    }, 500);

    // 折扣计算
    const discountByVal = (val: number) => {
        console.log('[editParams]', editParams);
        const discount = (tradeDetail?.payment?.originAmount || 0) * (val / 10);
        console.log('[discount]', discount);
        editOrderForm.setFieldsValue({ totalAmount: discount?.toFixed(2) });
        setEditParams({ ...editParams, totalAmount: discount });
    };

    // 单项折扣计算
    const discountByVal2 = (val: number) => {
        console.log('[editParams]', editParams);
        let discount = (singEditParams?.totalAmount || 0) * (val / 10);
        console.log('[discount]', discount);
        discount = Number(Number(discount).toFixed(2));
        editSingleOrderForm.setFieldsValue({ totalAmount: discount?.toFixed(2) });
        setSingleEditParams({ ...singEditParams, totalAmount: discount });
    };

    // 返回上一页
    const handleBack = () => {
        history.back();
    };

    // 渲染操作按钮
    const renderActionButtons = () => (
        <Card>
            <Space direction="vertical" style={{ width: '100%' }}>
                {tradeDetail?.status === 1 && (
                    <Button
                        danger
                        type="primary"
                        block
                        onClick={() => {
                            console.log('[tradeDetail]', tradeDetail?.payment?.originAmount);
                            editOrderForm.resetFields();
                            editOrderForm.setFieldsValue({
                                seat: tradeDetail?.seat,
                                tableId: tradeDetail?.restaurantTable?.id,
                                totalAmount: tradeDetail?.payment?.originAmount,
                            });
                            setEditParams({
                                seat: tradeDetail?.seat,
                                tableId: tradeDetail?.restaurantTable?.id,
                                totalAmount: tradeDetail?.payment?.originAmount,
                            });
                            setEditOpen(true);
                        }}
                    >
                        修改（折扣等）
                    </Button>
                )}

                {tradeDetail?.status === 1 && (
                    <Button
                        danger
                        type="primary"
                        block
                        onClick={() => setCheckoutModalOpen(true)}
                    >
                        结账（线下完单）
                    </Button>
                )}

                {tradeDetail?.status === 1 && (
                    <Popconfirm
                        title="确认清台吗"
                        key="delete"
                        onConfirm={async () => {
                            const resp = await cancelTrade(orderId!);
                            if (resp.code === 0) {
                                message.success('操作成功');
                                init();
                            }
                        }}
                    >
                        <Button danger type="primary" block>
                            清台（重置）
                        </Button>
                    </Popconfirm>
                )}

                {tradeDetail?.status === 1 && (
                    <Button
                        type="primary"
                        block
                        onClick={() => {
                            setOrderProductOpen(true);
                        }}
                    >
                        加单
                    </Button>
                )}

                {tradeDetail?.status === 1 && (
                    <Button
                        type="primary"
                        block
                        onClick={async () => {
                            const resp = await printTradeTicket(orderId!);
                            if (resp.code === 0) {
                                message.success('操作成功');
                                init();
                            }
                        }}
                    >
                        打印制作分单
                    </Button>
                )}

                <Button
                    type="primary"
                    block
                    onClick={async () => {
                        const resp = await printCashierTicket(orderId!);
                        if (resp.code === 0) {
                            message.success('操作成功');
                            init();
                        }
                    }}
                >
                    打印结账单
                </Button>
            </Space>
        </Card>
    );

    // 单件修改模态框
    const renderSingleEditModal = () => (
        <Modal
            title="单件修改"
            zIndex={102}
            open={singleEditOpen}
            onOk={async () => {
                console.log('singEditParams', singEditParams);
                let finalParams = makeTradeOrderList(tradeDetail?.orders);
                finalParams = finalParams.map((item) => {
                    if (item.orderId === singEditParams.orderId) {
                        return {
                            ...item,
                            price: singEditParams.totalAmount,
                        };
                    }
                    return item;
                });
                console.log('[finalParams]', finalParams);

                await handleEditOrder(finalParams);
                setSingleEditOpen(false);
            }}
            onCancel={() => {
                setSingleEditOpen(false);
                setSingleEditParams({});
                setCheckoutbindedUser(null);
                editSingleOrderForm.resetFields();
            }}
            destroyOnClose
        >
            <Card>
                <Form
                    form={editSingleOrderForm}
                    onValuesChange={(_, values) => {
                        console.log('[_,values]', _, values);
                        setSingleEditParams(values);
                    }}
                    initialValues={singEditParams}
                >
                    <Card>
                        <div className="">
                            折扣：
                            <InputNumber
                                placeholder="输入折扣自动计算"
                                style={{ width: '150px' }}
                                onChange={discountByVal2}
                            ></InputNumber>
                            <Row className="mt10" gutter={[10, 10]}>
                                <Col>
                                    <Button onClick={() => discountByVal2(6)}>6折</Button>
                                </Col>
                                <Col>
                                    <Button onClick={() => discountByVal2(8)}>8折</Button>
                                </Col>
                                <Col>
                                    <Button onClick={() => discountByVal2(8.8)}>8.8折</Button>
                                </Col>
                                <Col>
                                    <Button onClick={() => discountByVal2(9)}>9折</Button>
                                </Col>
                            </Row>
                        </div>

                        <Form.Item
                            className="mt10"
                            label="金额"
                            name={'totalAmount'}
                            rules={[{ required: true }]}
                        >
                            <InputNumber></InputNumber>
                        </Form.Item>
                    </Card>
                </Form>
            </Card>
        </Modal>
    );

    // 订单修改模态框
    const renderEditModal = () => (
        <Modal
            title="修改"
            zIndex={102}
            open={editOpen}
            onOk={() => {
                handleEditOrder();
                setEditOpen(false);
            }}
            onCancel={() => {
                setEditOpen(false);
                setEditParams({});
                setCheckoutbindedUser(null);
                editOrderForm.resetFields();
            }}
            destroyOnClose
        >
            <Card>
                <Form
                    form={editOrderForm}
                    onValuesChange={(_, values) => {
                        console.log('[_,values]', _, values);
                        setEditParams(values);
                    }}
                    initialValues={editParams}
                >
                    <Form.Item label="人数" name="seat">
                        <InputNumber></InputNumber>
                    </Form.Item>
                    <Form.Item
                        label="桌号"
                        name="tableId"
                        rules={[{ required: true, message: '请选择桌号' }]}
                    >
                        <Select>
                            {tableList.map((item) => (
                                <Select.Option key={item.id} value={item.id}>
                                    {item.name}
                                </Select.Option>
                            ))}
                        </Select>
                    </Form.Item>
                    {/* <Form.Item label="备注" name="remark">
                        <Input.TextArea></Input.TextArea>
                    </Form.Item> */}
                    <Card>
                        <div className="">
                            折扣：
                            <InputNumber
                                placeholder="输入折扣自动计算"
                                style={{ width: '150px' }}
                                onChange={discountByVal}
                            ></InputNumber>
                            <Row className="mt10" gutter={[10, 10]}>
                                <Col>
                                    <Button onClick={() => discountByVal(6)}>6折</Button>
                                </Col>
                                <Col>
                                    <Button onClick={() => discountByVal(8)}>8折</Button>
                                </Col>
                                <Col>
                                    <Button onClick={() => discountByVal(8.8)}>8.8折</Button>
                                </Col>
                                <Col>
                                    <Button onClick={() => discountByVal(9)}>9折</Button>
                                </Col>
                            </Row>
                        </div>

                        <Form.Item
                            className="mt10"
                            label="金额"
                            name={'totalAmount'}
                            rules={[{ required: true }]}
                        >
                            <InputNumber></InputNumber>
                        </Form.Item>
                    </Card>
                </Form>
            </Card>
        </Modal>
    );

    // 结账模态框
    const renderCheckoutModal = () => (
        <Modal
            title="结账"
            open={checkoutModalOpen}
            onOk={handleCheckout}
            onCancel={() => {
                setCheckoutModalOpen(false);
            }}
            zIndex={101}
            width={600}
        >
            <Card title="会员信息">
                <div className="flex" style={{ display: 'flex' }}>
                    <AutoComplete
                        placeholder="请输入会员手机号搜索"
                        style={{ width: '100%' }}
                        onChange={(v) => {
                            setMenberInputVal(v);
                            handleSearch(v);
                        }}
                        options={userOptions}
                        onSelect={(id) => {
                            getMenber(id);
                        }}
                        value={menberInputVal}
                    ></AutoComplete>
                    {checkoutUser && !checkoutBindedUser && (
                        <Button type="primary" style={{ marginLeft: '10px' }} onClick={bindMenber}>
                            绑定
                        </Button>
                    )}
                </div>

                {checkoutUser && (
                    <div style={{ marginTop: '20px' }}>
                        <Row justify="space-between">
                            <Col>余额：</Col>
                            <Col>￥{checkoutUser?.balance}</Col>
                        </Row>
                        <Row justify="space-between" style={{ marginTop: '10px' }}>
                            <Col>积分</Col>
                            <Col>{checkoutUser?.credit}</Col>
                        </Row>

                        <Form
                            form={menberForm}
                            style={{ marginTop: '20px' }}
                            layout="vertical"
                            onValuesChange={handlePreviewCheckout}
                        >
                            {!checkoutBindedUser && (
                                <div style={{ color: 'red', marginBottom: '10px' }}>* 请绑定会员后再进行下面操作</div>
                            )}

                            <Form.Item label="使用会员余额抵扣" name="useBalance">
                                <Switch disabled={!checkoutBindedUser}></Switch>
                            </Form.Item>
                            <Form.Item label="使用会员积分抵扣" name="useCredit">
                                <Switch disabled={!checkoutBindedUser}></Switch>
                            </Form.Item>
                        </Form>
                    </div>
                )}

                {!checkoutUser && <Empty style={{ marginTop: '20px' }} description="可输入手机号确认会员" />}
            </Card>

            <div style={{ marginTop: '20px' }}>
                {checkoutDetail && (
                    <div>
                        <Row justify="space-between">
                            <Col>余额抵扣：</Col>
                            <Col>￥{checkoutDetail?.balanceDeduction}</Col>
                        </Row>
                        <Row justify="space-between">
                            <Col>积分抵扣：</Col>
                            <Col>￥{checkoutDetail?.creditDeduction}</Col>
                        </Row>
                        <Row justify="space-between">
                            <Col>合计抵扣：</Col>
                            <Col>￥{checkoutDetail?.totalDeduction}</Col>
                        </Row>
                        <Divider></Divider>
                    </div>
                )}
                <Row justify="space-between">
                    <Col>总计金额：</Col>
                    <Col>
                        ￥
                        {checkoutDetail?.amount !== undefined
                            ? checkoutDetail?.amount
                            : tradeDetail?.payment?.amount}
                    </Col>
                </Row>
            </div>
        </Modal>
    );

    return (
        <PageContainer
            title={`订单详情: ${tradeDetail?.no || ''}`}
            onBack={handleBack}
        >
            <AddOrderProductModal
                visible={orderProductOpen}
                onClose={() => setOrderProductOpen(false)}
                onOk={async (vals) => {
                    await handleEditOrder(
                        [...makeTradeOrderList(tradeDetail?.orders), ...(vals as any)],
                        vals?.length,
                    );
                }}
            ></AddOrderProductModal>

            {renderSingleEditModal()}
            {renderEditModal()}
            {renderCheckoutModal()}

            <Spin spinning={loading}>
                <Row gutter={[20, 20]}>
                    <Col xs={24} sm={24} md={8} lg={6}>
                        <Card title="基础信息">
                            <Row>订单号： {tradeDetail?.no}</Row>
                            <Row style={{ marginTop: '10px' }}>开始就餐时间： {tradeDetail?.createdAt}</Row>
                            <Row style={{ marginTop: '10px' }}>桌号： {tradeDetail?.restaurantTable?.name || '暂无'}</Row>
                            <Row style={{ marginTop: '10px' }}>备注： {tradeDetail?.remark || '暂无'}</Row>
                        </Card>

                        <Card title="操作" style={{ marginTop: '20px' }}>
                            {renderActionButtons()}
                        </Card>
                    </Col>

                    <Col xs={24} sm={24} md={16} lg={18}>
                        <Tabs defaultActiveKey="1">
                            <TabPane tab="订单商品" key="1">
                                <Card>
                                    <Row>
                                        <Col span={24}>
                                            <Card title="价格信息" style={{ marginBottom: '16px' }}>
                                                <Row justify="space-between">
                                                    <Col>原价：</Col>
                                                    <Col>￥{tradeDetail?.payment?.originAmount}</Col>
                                                </Row>
                                                <Row justify="space-between">
                                                    <Col>调整：</Col>
                                                    <Col>￥{tradeDetail?.payment?.adjust}</Col>
                                                </Row>
                                                <Row justify="space-between">
                                                    <Col>折扣：</Col>
                                                    <Col>￥{tradeDetail?.payment?.discount}</Col>
                                                </Row>
                                                <Row justify="space-between" style={{ color: 'red' }}>
                                                    <Col>实际支付：</Col>
                                                    <Col>￥{tradeDetail?.payment?.amount}</Col>
                                                </Row>
                                            </Card>

                                            <div>
                                                <Row justify="space-between" style={{ marginBottom: '10px' }}>
                                                    <Col>操作员：</Col>
                                                    <Col>-</Col>
                                                </Row>
                                                <Row justify="space-between" style={{ marginBottom: '10px' }}>
                                                    <Col>创建时间：</Col>
                                                    <Col>{tradeDetail?.createdAt}</Col>
                                                </Row>
                                                <Row justify="space-between" style={{ marginBottom: '10px' }}>
                                                    <Col>修改时间</Col>
                                                    <Col>{tradeDetail?.updatedAt}</Col>
                                                </Row>
                                                <Row justify="space-between" style={{ marginBottom: '10px' }}>
                                                    <Col>状态：</Col>
                                                    <Col>
                                                        <OrderStatusTag status={tradeDetail?.status}></OrderStatusTag>
                                                    </Col>
                                                </Row>
                                            </div>

                                            <Form form={productListForm} component={false}>
                                                <Table
                                                    columns={mergedColumns as any}
                                                    dataSource={tradeDetail?.orders}
                                                    pagination={false}
                                                    style={{ marginTop: '10px' }}
                                                    components={{
                                                        body: { cell: EditableCell },
                                                    }}
                                                    rowKey="id"
                                                />
                                            </Form>
                                        </Col>
                                    </Row>
                                </Card>
                            </TabPane>
                            <TabPane tab="会员信息" key="2">
                                <Card>
                                    {tradeDetail?.user ? (
                                        <div>
                                            <Row justify="space-between" style={{ marginBottom: '10px' }}>
                                                <Col span={8}>会员名称：</Col>
                                                <Col span={16}>{tradeDetail.user.username}</Col>
                                            </Row>
                                            <Row justify="space-between" style={{ marginBottom: '10px' }}>
                                                <Col span={8}>手机号码：</Col>
                                                <Col span={16}>{tradeDetail.user.mobile}</Col>
                                            </Row>
                                        </div>
                                    ) : (
                                        <Empty description="未绑定会员" />
                                    )}
                                </Card>
                            </TabPane>
                        </Tabs>
                    </Col>
                </Row>
            </Spin>
        </PageContainer>
    );
};

export default OrderDetailPage;